import Taro from "@tarojs/taro";
/**
 * 被挂起的请求数组
 */
var refreshSubscribers = [];
/**
 * 刷新token 回调
 */
var refreshTokenFunc;
/**
 * token失效标识
 */
var refreshTokenFlag = false;
/**
 * push所有请求到数组中
 * @param cb
 */
var subscribeTokenRefresh = function (cb) {
    refreshSubscribers.push(cb);
};
/**
 * 刷新请求（refreshSubscribers数组中的请求得到新的token之后会自执行,用新的token去请求数据)
 * @param token
 */
var onRrefreshed = function (token) {
    if (refreshSubscribers.length == 0)
        return;
    refreshSubscribers.map(function (cb) { return cb(token); });
};
/**
 * 刷新token监听
 * @param callback
 */
var reigistRefreshTokenEvent = function (callback) {
    refreshTokenFunc = callback;
};
/**
 * 执行刷新token相关操作
 */
var triggerRefresh = function () {
    refreshTokenFlag = true;
    refreshTokenFunc().then(function (res) {
        onRrefreshed(res.token || "");
        refreshSubscribers = [];
        refreshTokenFlag = false;
    }).catch(function () {
        refreshSubscribers = [];
        refreshTokenFlag = false;
    });
};
/**
 * 执行刷新token以及调用后续接口逻辑
 * @param option
 */
var refreshToken = function (option) {
    // 执行刷新逻辑
    if (!refreshTokenFlag) {
        triggerRefresh();
    }
    return new Promise(function (resolve, reject) {
        subscribeTokenRefresh(function (token) {
            //替换token
            option.header.token = token;
            Taro.request(option)
                .then(function (res) {
                var code = res.data.code || res.statusCode;
                if (code === 200) {
                    resolve(res);
                }
            })
                .catch(function (err) {
                reject(err);
            });
        });
    });
};
/**
 * 根据接口返回code执行相关操作
 * @param res
 * @param option
 */
var handleResponse = function (res, option) {
    var code = res.data.code || res.statusCode;
    switch (Number(code)) {
        case 200: //成功
            return res;
        case 102: // 短token过期
            return refreshToken(option);
        default: {
            // 业务异常code码
            return res;
        }
    }
};
var baseRequest = function (option) {
    return Taro.request(option)
        .then(function (res) {
        return handleResponse(res, option);
    })
        .catch(function (e) {
        throw e;
    });
};
export { reigistRefreshTokenEvent, baseRequest };
